package com.aftersale.demo.entity;

import com.alibaba.fastjson.annotation.JSONField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
*@Author  空
*@Date    2023/10/23 20:23
*@Desc
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "com.aftersale.demo.entity.LoginUser",description = "登录用户封装类")
public class LoginUser implements UserDetails {
    @ApiModelProperty(value = "用户信息")
    private User user;
    @ApiModelProperty(value = "用户权限载入桥梁")
    private List<String> permissions;
    public LoginUser(User user,List<String> permissions){
        this.user=user;
        this.permissions=permissions;
    }

    @JSONField(serialize = false)
    @ApiModelProperty(value = "用户权限")
    /**
     * 存储SpringSecurity所需要的权限信息的集合,不被序列化到redis中
     */
    private List<GrantedAuthority> authorities;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
//        else if(permissions==null){
//            authorities=null;
//        }else{
//
//        }
        authorities = permissions.stream().
                map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
        //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
//        for(String permission:permissions){
//            SimpleGrantedAuthority authority=new SimpleGrantedAuthority(permission);
//            authorities.add(authority);
//        }

    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
